//
//  EraserRubber_ViewController.m
//  EraserRubber_2_SaijT
//
//  Created by 丁诚昊 on 15/12/2.
//  Copyright © 2015年 ZSTech.iOS.丁诚昊(831). All rights reserved.
//

#import "EraserRubber_VC.h"
#import "UIView+D_Geometry.h"
#import "DCH_3DSpaceLear.h"

/**
 * 写给Saijt的算法和设计思路: 核心就是根据撒种子的原理 构造一个(frame手写/Mas_EdgesMAS约束/NSContraint苹果约束)视图表层
 * 的矩形定义 然后截图这个frame所在的View层 如果没有层 trigger触发的时候添加一个隐士的UIView 然后截取这个UIView所在的背景图片
 * 根据苹果的涂层树算法 只要附加在北京图片上的UIView的透明度低于 0.125f 就直接能够截图 3层View所在的底层View 也就是一张被污染过
 * 的图片 苹果的算法也不是很复杂
 */
typedef struct pool_buffered_width_height_structs
{
    CGFloat maxX;
    CGFloat maxY;
}struts_bufferWH;

@interface EraserRubber_VC ()
/**截图生成的触发条件 我这里假设是长按操作迭代30次之后 自动生成截图一张 命名为1.png 在bundle当前目录*/
@property (assign,atomic,setter=makeFlag:,getter=isTime2Capture) BOOL automaticllyPictureScreenMakeTrigger; //...
/**截图遮盖*/
@property (nonatomic,weak,readonly) UIView* captureView;
/**最大宽度和高度XY值的高速缓存区间*/
@property (assign,nonatomic) struts_bufferWH *bufferdXY; //....
@end

@implementation EraserRubber_VC
///不为无聊之事 何以遣有涯之生 - By:西毒欧阳峰
- (void)viewDidLoad {
    [super viewDidLoad];

    /// 添加长按手势 也可以更换其他手势识别器
    [self dependencyOfCGAnimatingOnRecongnisation:self];//AOP:--->依赖注入长按手势Target&Action函数指针
    
    ///init bgimageView
    [self initBGImageView];
    
    ///init capture button
    [self initButton];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

    NSLog(@"报告 ： 内存吃进");
}

-(void) initBGImageView
{
    CGRect bgframe = CGRectMake(0, 0, kscreemWidth, 400);
    __strong UIImageView* bgView = [[UIImageView alloc] initWithFrame:bgframe];
    bgView.image = [UIImage imageNamed:@"22"];
    
    [self.view addSubview:bgView];
    self.view.contentMode = UIViewContentModeCenter;
    
    UIImageView* logoView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo1"]];
    [self.view addSubview:logoView];
    CGRect imgFrame = (CGRect){{10,10},{44,44/2}};
    logoView.frame = imgFrame;
}

-(void) initButton
{
    UIButton* rectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:rectButton];
    rectButton.backgroundColor = [UIColor whiteColor];
    [rectButton setTitle:@"点击生成截图" forState:0];
    [rectButton setTitleColor:[UIColor blackColor] forState:0];
    rectButton.D_Size = CGSizeMake(120, 44);
    rectButton.center = CGPointMake(RadiusDefaultValue+rectButton.D_Size.width/2, kscreemHeight - RadiusDefaultValue - rectButton.D_Size.height/2);
    [rectButton addTarget:self action:@selector(captureAreaWithDots) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - Target & Action
-(void) dependencyOfCGAnimatingOnRecongnisation:(UIViewController*)viewController{///要么摇滚青春 要么陨落星辰
    UILongPressGestureRecognizer* lpGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(seekingIt:)];
    [viewController.view addGestureRecognizer:lpGestureRecognizer];
}
static int counter = 1;
-(void) seekingIt:(nonnull UIGestureRecognizer*)gestureRecognizer{///量子与情感 真理与决断
    CGPoint touchPoint = [gestureRecognizer locationInView:self.view];
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        self.bufferdXY = (struts_bufferWH*)malloc(sizeof(struts_bufferWH));
        self.bufferdXY->maxX = 0.0f;
        self.bufferdXY->maxY = 0.0f;
    });
    DCH_3DSpaceLear* DCH_DotsView = [DCH_3DSpaceLear fancyColorCypherView];
    [self.view addSubview:DCH_DotsView];
    DCH_DotsView.D_Size = CGSizeMake(RadiusDefaultValue*2, RadiusDefaultValue*2);
    DCH_DotsView.center = touchPoint;
    counter++;
    if ((touchPoint.x + RadiusDefaultValue) >= self.bufferdXY->maxX) {
        self.bufferdXY->maxX = touchPoint.x + RadiusDefaultValue;
    }
    if ((touchPoint.y + RadiusDefaultValue) >= self.bufferdXY->maxY) {
        self.bufferdXY->maxY = touchPoint.y + RadiusDefaultValue;
    }
}

///开始刷新[缓存] ---> 截图
-(void) captureAreaWithDots
{
    [self makeFlag:YES];
    __block CGFloat beginX,endX,startY,finishY;
    beginX = self.bufferdXY->maxX;
    startY = self.bufferdXY->maxY;
    
    ///遍历获取最小值x,y
    [self.view.subviews enumerateObjectsUsingBlock:^(__kindof DCH_3DSpaceLear * _Nonnull dotsView, NSUInteger idx, BOOL * _Nonnull stop) {
        if([dotsView isKindOfClass:[DCH_3DSpaceLear class]])
        {
            NSLog(@"beginX = %2f",beginX);
            if (beginX >= dotsView.D_Left)
            {
                beginX = dotsView.D_Left; ///如果左边界float值比最小大 就交换指针的解引用
            }
            if (startY >= dotsView.D_Top)
            {
                startY = dotsView.D_Top;///如果上边界float值比最小大 就交换指针的解引用
            }
        }
    }];
    
    ///从高速缓存池pull一对最大值XY值出来构建矩形
    NSLog(@"{minX_%2f,minY_%2f}",beginX,startY);
    endX = self.bufferdXY->maxX;
    finishY = self.bufferdXY->maxY;
    
    /// make DCHLayer
    if(self.isTime2Capture)
    {
        CGRect inVisibleLayerFrame = (CGRect){{beginX,startY},{endX-beginX,finishY-startY}};
        UIView *layerView = [UIView new];
        [self.view addSubview:layerView];
        layerView.alpha = 0.0f;
        [UIView animateWithDuration:1.2f animations:^{
            NSLog(@"矩形--->%@",NSStringFromCGRect(inVisibleLayerFrame));
            layerView.frame = inVisibleLayerFrame;
            self.view.userInteractionEnabled = NO;
            layerView.backgroundColor = [UIView randomColor];
            layerView.alpha = .750f;
        }completion:^(BOOL finished) {
            [self makeFlag:NO];
            layerView.layer.borderColor = [[UIView randomColor] CGColor];
            layerView.clipsToBounds = YES;
            layerView.layer.cornerRadius = 5.5f;
            layerView.alpha = .25f;
            
            [self clipBtnClicked:inVisibleLayerFrame];
            self.view.userInteractionEnabled = YES;
        }];
    }
}

/**
 *剪裁 网上抄的代码 除了问题我不负责！
 */
static int ScreenshotIndex=0; //这里的逻辑直接采用上面博主的逻辑了
- (void)clipBtnClicked:(CGRect)frame{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(kscreemWidth, kscreemHeight), YES, 0.0f);     //设置截屏大小
    [[self.view layer] renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRef imageRef = viewImage.CGImage;
    CGImageRef imageRefRect = CGImageCreateWithImageInRect(imageRef, frame);
    UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];
    
    NSData *imageViewData = UIImagePNGRepresentation(sendImage);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pictureName= [NSString stringWithFormat:@"screenShow_%d.png",ScreenshotIndex];
    NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:pictureName];
    //这里我将路径设置为一个全局String，这里做的不好，我自己是为了用而已，希望大家别这么写
    NSString* path_OS_X = @"/Users/DCH831/Desktop/12.png";
    [imageViewData writeToFile:path_OS_X atomically:YES];
    [imageViewData writeToFile:savedImagePath atomically:YES];//保存照片到沙盒目录
    UIImageWriteToSavedPhotosAlbum(sendImage, nil, nil, nil);//保存图片到照片库
    CGImageRelease(imageRefRect);
    ScreenshotIndex++;
}
#pragma mark - Getter & Setter & Misc
- (UIView *)captureView{
    UIView *view = [[UIView alloc] init];
    [self.view addSubview:view];
    view.backgroundColor = [UIColor redColor];
    return view;
}
@end
